/**
 * karin 2017/3/22
 * 年检手续办理
 */
import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import _ from 'lodash'

// 加载actions
import taxCheckInfoService from '../../services/taxCheckInfoService'
// 加载json
import {defaultData, rightA, rightB} from './defaultData'

// 加载样式
import Style from './index.scss'

// 加载组件
import IconText from '../../components/calculatorOfYearlyCheck/iconText'
import CheckList from '../../components/CheckAndArrow'
import {WhiteSpace, Toast} from 'antd-mobile'
import ReModal from '../../components/common/reModal'
import Service from '../../components/common/customerService'
import {getWeixinConfig} from '../../actions/homeAction'
import {getViolationUrl} from '../../actions/annualInspectionAction';
//加载依赖
import AlipayJSOperation from '../../utils/alipayJSOperation'
import jsApi from '../../utils/cx580.jsApi'
import typeOfBrowser from '../../utils/typeOfBrowser'
import PageBar from '../../components/common/pageBar'
import SendCxytjMessage from '../../utils/sendCxytjMessage'
import appVersion from "../../utils/appVersion";
/*import BackMeanSure from '../../utils/backMeanSure';*/

// 组件

class AnnualInspection extends Component {
    constructor(props) {
        super(props);

        this.state = {
            car: {
                num: '',
                days: '?',
                violaNum: 0, // 违章条数，默认为0，所有违章条数+1，方便实现不同效果
            },
            states: -1,//年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废
            data: [], //
            footnote: false, // 进口车，脚注
            attentions: [],
            confirmStatus: 0,//当前确认状态，用于控制当且列表是否可点击
        };
        this.orderId = this.props.params.orderId; // carId
        this.closeAliModal = this.closeAliModal.bind(this); // 关闭弹窗
        this.carInfoForOrderId = {
            name: '',
            phone: '',
            carId: '',// 车牌ID
            mailType: '',
            inspectionType: 0 // 年检类型：1，免检；2，过线检
        };
        // this.backMeanSureInstance = new BackMeanSure(this.goHome.bind(this), 'annualInspection');
    }


    //返回首页
    goHome(back, stay, toUrl) {
        if (typeOfBrowser.getChannelOfBrowser() == 'app') {
            //app直接关闭当前webview回到年检提醒
            jsApi.call(
                {
                    "commandId": "",
                    "command": "close"
                }
            )
        }
        else {
            history.pushState({}, '', '');
            let backNumber = -1 * history.length + 1;
            history.go(backNumber);
        }
    }

    /**
     * 生命周期
     */
    // 为了跳转，记录
    componentWillReceiveProps() {
        if (localStorage.getItem('JumpOut')) {
            // 这个数据是为了判断是否跳出年检浏览器
            let that = this;
            setTimeout(function () {
                that.getByOrderId(localStorage.getItem('JumpOut'));
                localStorage.removeItem('JumpOut'); // 这个数据是为了判断是否跳出年检浏览器
            }, 200);
        }
    }

    componentWillMount() {
    }

    componentWillUnmount() {
        this.closeAliModal(); //关闭弹窗
        AlipayJSOperation.removeLeftButtonEvent();
    }

    componentDidMount() {
        // 添加标题
        document.querySelector("title").innerHTML = "办理资料确认"
        // window.onShowHtml = () => this.update();//重新回到栈顶
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false)
        //设置标题
        AlipayJSOperation.setTitle('办理资料确认')
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE')

        //   判断：没有订单，则返回
        if (!this.orderId) {
            Toast.info('没有车辆订单信息，请重新进入', 2, () => {
                window.history.back()
            }, true);
            return;
        }

        // 请求：通过订单号，得到车辆相关数据
        this.getByOrderId(this.orderId);
        //拦截返回事件，直接返回首页
        //  this.backMeanSureInstance.bindBackMeansure();


        //屏蔽微信分享
        this.WeXinOperation();
    }

    componentWillUnmount() {
    }

    WeiXinConfig(config) {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: config.appId, // 必填，公众号的唯一标识
            timestamp: config.timestamp, // 必填，生成签名的时间戳
            nonceStr: config.nonceStr, // 必填，生成签名的随机串
            signature: config.signature,// 必填，签名，见附录1
            jsApiList: ['hideOptionMenu', 'closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(() => {
            wx.hideOptionMenu();
        });
    }

    //微信屏蔽分享功能
    WeXinOperation() {
        if (typeOfBrowser.getChannelOfBrowser() == 'weixin') {
            this.props.dispatch(getWeixinConfig({signUrl: location.href}, (result) => {
                this.WeiXinConfig(result);
                //切换页面时再次触发微信配置
                window.addEventListener('hashchange', (e) => {
                    this.WeiXinConfig(result);
                }, false);
            }))
        }
    }

    //发送初始化埋点数据
    sendInitMessage(inspectionType) {
        let eventId = inspectionType == 1 ? 'H5_P_Interspection_EnterOnlineComfirmpage' : 'H5_P_Interspection_EnterComfirmpage';
        SendCxytjMessage.sendMessage({eventId: eventId});
    }


    /**
     * 事件
     * ifGetViolaNum: 这个为true，请求违章条数
     */

    // 请求：通过订单号，得到车辆相关数据
    getByOrderId(orderId) {
        // 发出请求
        let postData = {
            orderId: orderId
        };
        Toast.hide();
        Toast.loading("", 10, () => Toast.info("网络错误", 2));
        let carInfoForOrderId = this.carInfoForOrderId;
        taxCheckInfoService.getInfo(postData).then(resultData => {
            //  console.log('+++++++网络请求 = ',data,resultData);

            if (resultData.code == 1000) {
                let result = resultData.data;
                carInfoForOrderId = Object.assign(carInfoForOrderId, {
                    name: result.name,
                    phone: result.phone,
                    carId: result.carId,// 车牌ID
                    mailType: result.mailType,
                    inspectionType: result.inspectionType // 年检类型：1，免检；2，过线检
                });

                let days = result.checkDate == '' ? '?' : result.days

                this.setState({
                    car: Object.assign(this.state.car, {
                        num: result.carNumber,
                        days: days,
                    }),
                    states: result.state,
                });
                this.sendInitMessage(result.inspectionType) // 埋点
            }
            else {
                Toast.info(resultData.msg, 2);
            }
        }).then(() => {
            this.getRequirementsByorderID(this.orderId)
        })

    }

    // 请求：通过carID，得到车辆违章数据
    getBycarID(carID) {
        // 发出请求
        let postData = {
            carId: carID
        };
        taxCheckInfoService.getViolaNum(postData).then(resultData => {
            if (resultData.code == 1000) {
                let result = resultData.data;
                //   alert("通过carID，得到车辆违章数据 ="+JSON.stringify(result));
                // 处理请求得到的数据
                let dataViolaNum = typeof (result.violationCount) == 'undefined' ? 0 : result.violationCount + 1 // 这里加1是为了和没查询区别
                //  console.log('++++++++++++这里是为了 判断是否更新3', result, typeof (result.violationCount) == 'undefined');
                //dataViolaNum =0，表示无法查询，1表示查询后没有违章，n表示查询后几条违章


                let ActualData = dataViolaNum - 1; // 还原data_violaNum，实际违章条数
                let data = this.state.data;
                switch (dataViolaNum) {
                    case 0:
                        // 没有数据
                        break;
                    case 1:
                        data[0].check = 1;
                        this.setState({
                            data: data
                        });
                        break;
                    default:
                        data[0].check = 2;
                        rightA[2] = '有' + ActualData + '条未处理违章'
                        this.setState({
                            data: data
                        });
                        break
                }


                // 输出
                this.setState({
                    car: Object.assign(this.state.car, {
                        violaNum: dataViolaNum,
                    })
                });

                this.changeONECheckData();
                Toast.hide();
            }
            else {
                Toast.info(resultData.msg, 2);
            }
        })
    }

    // 通过 orderId ,拿到 年检手续条件
    getRequirementsByorderID(orderId) {
        // 发出请求
        let postData = {
            orderId: orderId
        };
        taxCheckInfoService.getvaillData(postData).then(resultData => {
            if (resultData.code == 1000) {
                Toast.hide();
                let datas = resultData.data.requirements;
                let attentions = resultData.data.attentions;
                let arrData = [];
                //缓存当前确认状态，用于控制当且列表是否可点击
                this.setState({
                    confirmStatus: resultData.data.confirmStatus
                });
                arrData.push(_.cloneDeep(defaultData['WZ'])); // 加入违章的提示
                for (let i = 0; i < datas.length; i++) {
                    let element = _.cloneDeep(defaultData[datas[i].requirementType]);
                    //99是底部进口车说明的提示
                    if (datas[i].requirementType == 'OTHER') {
                        this.setState({
                            footnote: true
                        })
                    } else {
                        element.check = datas[i].status;
                        element.documentId = datas[i].id;//资料id赋值
                        element.tlt = datas[i].requirementName;//名称由后端获取
                        element.confirmType = datas[i].confirmType;//由后端传入的字段控制用户能否自行审核
                        arrData.push(element)
                    }
                }

                this.setState({
                    data: arrData,
                    attentions: attentions,
                })
            }
            else {
                Toast.info(resultData.msg, 2);
            }
        }).then(() => {
            this.getBycarID(this.carInfoForOrderId.carId)
        })
        //  拿到年检资料列表


    }

    // 页面跳转
    toURL(url) {
        this.context.router.push(url)
    }

    //判断是否有审核状态
    containsExamine() {
        let data = this.state.data; // 数据
        for (let i = 1; i < data.length; i++) {
            //存在审核中状态
            if (data[i].check == 2) {
                return 2;
            }
            //存在审核失败状态
            else if (data[i].check == 4) {
                return 4;
            }
        }
        return -1;
    }

    // 判断是否都勾选了， 返回为true
    changeONECheckData() {

        let data = this.state.data; // 数据
        let dataLEN = 0;
        for (let i = 1; i < data.length; i++) {
            // 1:已确认，3：审核通过，5：在有效期内，7：已备好，2：审核中，4：审核失败（2,4仅能点击，点击后弹出提示）
            if (data[i].check == 1 || data[i].check == 3 || data[i].check == 5 || data[i].check == 7 || data[i].check == 2 || data[i].check == 4) dataLEN++
        }
        // 如果违章有违章，则 (dataLEN+1) == data.length，无违章则 (dataLEN+1) >= data.length
        return (data.length > 0 && (dataLEN + 1) >= data.length) ? true : false

    }

    // 埋点
    sendMessageBykey(key) {
        var eventId;
        switch (key) {
            case 'WZ':
                eventId = 'Insepection_ExemptionDataConfirm_CheckViolation';
                break;
            case 'JQX':
                eventId = 'H5_E_Interspection_CheckInsurance';
                break;
            case 'CCS':
                eventId = 'H5_E_Interspection_CheckTax';
                break;
            case 'XSZ':
                eventId = 'H5_E_Interspection_CheckLicense';
                break;
            case 'CLDJZ':
                eventId = 'H5_E_Interspection_CheckRegistrationcertificate';
                break;
            case 'SFZ':
                eventId = 'H5_E_Interspection_CheckID';
                break;
            case 'SCSFZ':
                eventId = 'H5_E_Interspection_CheckIDPicture';
                break;
        }
        SendCxytjMessage.sendMessage({
            eventId: eventId,
            attr1: this.state.inspectionType //属性1
        });
    }

    //正常渠道跳转到违章
    gotoNormalViolation(violaNum) {
        let production = (window.location.href.indexOf('annualcheck.cx580.com/') > -1 || window.location.href.indexOf('pre.cx580.com') > -1) ? true : false; //是否为生产环境

        let baseApiUrl = production ? "https://daiban.cx580.com" : "http://webtest.cx580.com:9021";//  192.168.2.225
        let userId = sessionStorage.getItem('userId'),
            token = sessionStorage.getItem('token'),
            userType = sessionStorage.getItem('userType'),
            authType = sessionStorage.getItem('authType');
        // let wzuserChannel = typeOfBrowser.getChannelOfBrowser();

        let url = baseApiUrl + '/Violation/index.html?authType=' + authType + '&userType=' + userType + '&userId=' + userId + '&token=' + token;
        if (violaNum == 0) {
            if (this.state.car.num.indexOf('粤') >= 0) {
                window.location.href = `${baseApiUrl}/AddCar/index.html?authType=${authType}&userType=${userType}&userId=${userId}&token=${token}#/authPage/${encodeURIComponent(this.state.car.num)}/0/0/0`;
            }
            else {
                // 编辑车辆页面
                // window.location.href = url + '#/replenishInfo/' + this.carInfoForOrderId.carId;
                window.location.href = `${baseApiUrl}/AddCar/index.html#/addCar/${this.state.car.num}`;
            }
        }
        else {
            window.location.href = url + '#/violationList/' + this.carInfoForOrderId.carId;
        }
    }

    //京东跳转到违章
    gotoJDViolation() {
        this.props.dispatch(getViolationUrl({carId: this.carInfoForOrderId.carId}, (resultUrl) => {
            location.href = resultUrl;
        }))
    }

    //淘宝及天猫跳转到违章
    gotoTaobaoViolation() {
        location.href = `https://cxy580.ews.m.jaeapp.com/?token=${sessionStorage.getItem('token')}&userType=${sessionStorage.getItem('userType')}`;
    }

    //跳转到违章
    goToViolation(violaNum) {
        if (sessionStorage.getItem('userType') == 'jindongns2016') {
            this.gotoJDViolation()
        }
        else if (sessionStorage.getItem('userType') == 'SJTB2017' || sessionStorage.getItem('userType') == 'CXYTMALL') {
            this.gotoTaobaoViolation();
        }
        else {
            this.gotoNormalViolation(violaNum);
        }
    }

    //返回（CheckAndArrow组件返回的数据） 表单里面选择的情况：返回是哪个字段加入点击
    getCheckData(type, documentId, status, confirmType) {
        //状态为1,2,3时表示已经确认过，此时不应该再修改资料
        if (this.state.confirmStatus == 1 || this.state.confirmStatus == 2 || this.state.confirmStatus == 3) {
            return;
        }

        let that = this;
        let data = this.state.data;
        let violaNum = this.state.car.violaNum;
        let carId = this.carInfoForOrderId.carId;
        let carnumber = encodeURIComponent(this.state.car.num);
        let inspectionType = this.carInfoForOrderId.inspectionType || '1';
        let mailType = this.carInfoForOrderId.mailType || 'person';

        // 请求：通过订单号，得到车辆相关数据
        // this.getByOrderId(this.orderId,true);

        if (localStorage.getItem('detailUserType')) {
            sessionStorage.setItem('detailUserType', localStorage.getItem('detailUserType'));
            //  localStorage.removeItem('detailUserType');
        }

        let userChannel = typeOfBrowser.getChannelOfBrowser();
        switch (sessionStorage.getItem('detailUserType')) {
            case 'AliPayCityS2017':
                userChannel = typeOfBrowser.getChannelOfBrowser();
                break;
            case 'QQqianbao2017':
                userChannel = 'QQqianbao2017';
                break;
        }
        //  alert("userChannel = "+userChannel +' , carnumber = '+carnumber)

        //发送埋点数据
        this.sendMessageBykey(type);
        /**
         * key是1，2，3，表示是车船税等页面返回; key是 0 表示跳转到外面的违章页面。
         */
        if (type !== 'WZ' && (status == 2 || status == 3 || status == 4)) {
            this.toURL(`/uploadResult/${documentId}`);
            localStorage.removeItem('JumpOut');
        }
        else if (confirmType == 1) {
            this.toURL(`/uploadPage/${type}/${documentId}/1`);
            localStorage.removeItem('JumpOut');
        }
        else if (type !== 'WZ') {
            this.toURL(`/taxConfirm/${documentId}/${type}/${inspectionType}/${mailType}/${carnumber}/${confirmType}`);
            localStorage.removeItem('JumpOut');
        }
        else {
            // 查违章--网址跳转 -- 支付宝
            localStorage.setItem('JumpOut', this.orderId); // 这个数据是为了判断是否跳出年检浏览器,存在就是跳出去了
            let userType = localStorage.userType;
            Toast.loading('');

            /**
             * 切换生产或测试环境
             */
            let production = (window.location.href.indexOf('annualcheck.cx580.com/') > -1 || window.location.href.indexOf('pre.cx580.com') > -1) ? true : false; //是否为生产环境

            let baseApiUrl = production ? "https://daiban.cx580.com" : "http://192.168.1.168:9021";//  192.168.2.225


            /**
             * 判断浏览器，跳转到违章的相对应页面
             * violaNum =0，表示查不到违章
             */

            if (userChannel == 'app') {

                //app支付
                ///解决打开外部网址返回为空的问题，需要使用新VIEW打开页面跳转
                let urlOfNow = window.location.href;
                let APPbaseApiUrl = urlOfNow.replace(window.location.hash, '').split('?')[0].replace('#/', '');

                //6.3.3以上使用3.0sdk，参数发生变化
                let target = 'violationlist';
                if (appVersion.getMainVersionByCount() >= 6.33) {
                    APPbaseApiUrl = APPbaseApiUrl + '?api_version=3';
                    target = 'violationList';
                }

                jsApi.call({
                    'commandId': '',
                    'command': 'openNewBrowserWithURL',
                    'data': {
                        'url': `${APPbaseApiUrl}#/newAppUrl/${target}/${carnumber}/${carId}`,
                        'umengId': 'cfw_youkachongzhi',
                        'showTitleLayout': 'false' //是否显示到导航栏
                    }
                }, function (data) {
                });


            } else {
                this.goToViolation(violaNum);
            }


        }

    }

    //提交埋点发送
    sendSubmitMessage() {
        let eventId = this.state.inspectionType == 1 ? 'Insepection_ExemptionDataConfirm_SendData' : 'Insepection_OnlineDataConfirm_Done';
        SendCxytjMessage.sendMessage({eventId: eventId});
    }

    // 寄送：按钮
    submit(ifGoOn) {
        // 没有全选，按钮是灰色
        if (!this.changeONECheckData()) {

            // 按钮是灰色，所以不反应
            return false
        }
        if (this.containsExamine() == 2 || this.containsExamine() == 4) {
            let warning = '';
            if (this.containsExamine() == 2) {
                warning = '您的资料正在审核中，请等待资料都审核通过再进行下一步';
            }
            else {
                warning = '您有资料未审核通过，请重新上传并审核通过后再进行下一步';
            }
            ReModal.alert(warning);
            return false;
        }
        // 有违章，弹窗提示:查看违章情况
        if (!ifGoOn) {
            if (this.state.car.violaNum != 1) {
                ReModal.confirm('您尚有违章未办理，是否先寄送资料再办理违章？', () => {
                    this.submit(true)
                });
                return false
            }
        }

        // 发出请求
        Toast.hide();
        Toast.loading("", 10, () => Toast.info("网络错误", 2));
        let postData = {
            userId: 0,
            orderId: this.orderId,
            name: this.carInfoForOrderId.name,
            phone: this.carInfoForOrderId.phone,
        };
        if (this.carInfoForOrderId.inspectionType == 2) {

            taxCheckInfoService.sendData(postData).then(resultData => {
                Toast.hide();
                if (resultData.code == 1000) {
                    this.toURL(`/sendTheAddress/overLine/${this.orderId}`);//旧版
                }
                else {
                    Toast.info('网络异常', 2);
                }
            });
        }
        else {
            taxCheckInfoService.sendDataFree(postData).then(resultData => {
                Toast.hide();
                if (resultData.code == 1000) {
                    this.toURL(`/mailingAddress/${this.orderId}`);
                }
                else Toast.info('网络异常', 2);
            });
        }
        this.sendSubmitMessage();
    }


    // 弹窗相关事件，showModal、onClose
    //清除ant弹框
    closeAliModal() {
        let div = document.querySelector('.am-modal-wrap');
        if (div) {
            div = div.parentNode;
            if (div) {
                div.parentNode.removeChild(div);
            }
        }
    }

    /**
     * 组件
     */
    ////states:年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废
    render() {

        // 右上角年检天数提示
        let statesDOM = '';
        switch (this.state.states) {
            case 0:
                statesDOM = '距可预约时间';
                break;
            case 2:
            case 3:
            case 4:
                statesDOM = '年检已逾期';
                break;

            default:
                statesDOM = '年检剩余时间';
                break;
        }


        // 执行
        return (
            <div>
                <PageBar title='办理资料确认' back={() => {
                    jsApi.call(
                        {
                            "commandId": "",
                            "command": "close"
                        })
                }
                }/>
                <div className='cf plr30 pt50'>
                    <div className={Style.iconText + ' color111 font-34 fl'}>
                        <IconText imgUrl='./images/carNumber.png' text={this.state.car.num}/>
                    </div>
                    <div className='coloraaa font-26 fr'>{statesDOM} <span
                        className='color000'>{this.state.car.days}</span> 天
                    </div>
                </div>
                <WhiteSpace size='md'/>

                <div className='plr30 bg-white '>
                    <WhiteSpace size='xs'/>
                    <div className='cf ptb30'>
                        <div className='color666 font-30'>请确认以下信息以便完成年检办理</div>
                    </div>

                    {this.state.data.map((item, i) => {
                        return <CheckList className={Style.borderT} key={i}
                                          tips={i == 0 && this.state.car.violaNum != 1 ? '请查办违章后再继续办理年检' : ''}
                                          type={item.type}
                                          label={item.tlt}
                                          value={item.type != 'WZ' ? rightB[item.check] : rightA[item.check]}
                                          status={item.check}
                                          onClick={(type) => this.getCheckData(type, item.documentId, item.check, item.confirmType)}/>
                    })}

                </div>

                {this.state.footnote &&
                <div className='pt20 plr30 color999'><p>1.若您的车是进口车需提供车辆购置税完税证明原件或车辆铭牌照片打印件</p><p>2.若办理的是公司车需提供委托书原件</p>
                </div>}

                {this.state.attentions.length > 0 ? <div className={Style.tips}>
                    <div className={Style.title}>
                        <div></div>
                        <div className={Style.text}>温馨提示</div>
                        <div></div>
                    </div>
                    {this.state.attentions.map((item, index) => {
                        return <p key={index}>
                            {item.attention}
                        </p>
                    })}
                </div> : ''}
                <div className={Style.blank}>

                </div>

                <div className={Style.bottomButton}>
                    <Service className={Style.ServiceType} fixed={false} bottomText="客服"/>
                    <button className={this.changeONECheckData() ? Style.btn : Style.unableBtn}
                            onClick={() => this.submit(false)}>确认，前往下一步
                    </button>
                </div>

                {/*<Service className={Style.ServiceType} rightText='联系客服'/>*/}
            </div>
        );
    }
}

// AnnualInspection.propTypes = {
//     data: React.PropTypes.array
// };

// 默认值
AnnualInspection.defaultProps = {}


//使用context
AnnualInspection.contextTypes = {
    router: React.PropTypes.object.isRequired
}


export default connect()(AnnualInspection)